package com.example.common.interceptor;

import cn.hutool.json.JSONObject;
import com.example.common.annotation.Anon;
import com.example.common.util.JwtUtil;
import com.example.status.HttpStatus;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * @Description token拦截器
 * @Author Moran
 * @Date 2023-05-28 17:23
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 拦截验证
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置返回值属性
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String token = request.getHeader("token");
        PrintWriter out;
        // 对于注解的判断
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.getMethodAnnotation(Anon.class) != null || handlerMethod.getBeanType().isAnnotationPresent(Anon.class)) {
            //拥有Anon匿名访问注解的方法直接放行
            return true;
        }
        if (token != null) {
            //解析token
            Claims claims = null;
            try {
                claims = JwtUtil.parseToken(token);
            } catch (Exception e) {
                throw new Exception("token解析失败！");
            }
            if (claims != null) {
                request.setAttribute("user_claims", claims);
                return true;
            }
        }
        JSONObject res = new JSONObject();
        res.put("code", HttpStatus.UNAUTHORIZED);
        res.put("msg", "Sorry, Token is expired or unAuthorized!");
        out = response.getWriter();
        out.append(res.toString());
        return false;
    }
}
